/**
 * 还没写好
 */



const require = createRequire(import.meta.url);
import { segment } from "oicq";
import fetch from "node-fetch";
import plugin from "../../lib/plugins/plugin.js";
import gsCfg from "../genshin/model/gsCfg.js";
import { createRequire, syncBuiltinESMExports } from "module";
import cfg from "../../lib/config/config.js";
const fs = require("fs");
const path = require("path");

const serverAddress = "http://127.0.0.1:6969/";
const redisCDkey = `Yunzai:AIDraw:CD`;
const tempRedisCDkey = `Yunzai:AIDraw:tempCD`;
const redisSwitchKey = `Yunzai:AIDraw:OpenOrClose`;
const redisRecallKey = `Yunzai:AIDraw:Recall`;
if ((await redis.get(redisRecallKey)) == null) {
    await redis.set(redisRecallKey, 30); //默认撤回CD30秒
}

export class example extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: "AI画图",
            /** 功能描述 */
            dsc: "简单开发示例",
            /** https://oicqjs.github.io/oicq/#events */
            event: "message",
            /** 优先级，数字越小等级越高 */
            priority: 5000,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: "^(AI|)画图帮助",
                    /** 执行方法 */
                    fnc: "help",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^AI画图 ",
                    /** 执行方法 */
                    fnc: "draw",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^开启AI画图$",
                    /** 执行方法 */
                    fnc: "open",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^关闭AI画图$",
                    /** 执行方法 */
                    fnc: "close",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^快速画图 ",
                    /** 执行方法 */
                    fnc: "fastDraw",
                },
                {
                    /** 命令正则匹配 */
                    reg: "^设置撤回CD ",
                    /** 执行方法 */
                    fnc: "setRecallCD",
                },
            ],
        });
    }
    async setRecallCD(e) {
        if (e.user_id != cfg.masterQQ) {
            e.reply("你没有权限");
            return false;
        } else {
            let recallCD = e.raw_message.match(/(?<=设置撤回CD ).*/)[0];
            await redisRecallKey.set(redisRecallKey, recallCD);
            e.reply(`设置成功，现在的撤回CD是 ${recallCD} 秒`);
        }
    }

    async help(e) {
        e.reply(
            `AI画图帮助：\n高质量画图(但是速度慢)：AI画图+空格+关键字\n快速画图：快速画图+空格+关键字\n关键字只能是英文，关键字与关键字之间用英文逗号隔开`
        );
    }
    async fastDraw(e) {
        //判断是否开启
        let a = await redis.get(redisSwitchKey);
        if (a) {
            e.reply(`AI画图已关闭`);
            return false;
        }
        // 检查CD;
        let tempCd = await redis.get(tempRedisCDkey);
        if (tempCd) {
            let timeRemaining = await redis.ttl(redisCDkey);
            e.reply(`AI画图还未完成，请稍后再试`);
            return false;
        }
        console.log(e.raw_message);
        const msg = e.raw_message.match(/(?<=快速画图 ).*/)[0];
        //检查是否包含违禁词
        if (msg.match(/nsfw/)) {
            e.reply("不许涩涩！");
            return false;
        }
        e.reply("正在生成图片，预计需要1分钟...");
        await redis.set(tempRedisCDkey, 1, { EX: 60 });
        this.getDraw("快速画图", msg, e);
    }
    async draw(e) {
        //判断是否开启
        let a = await redis.get(redisSwitchKey);
        if (a) {
            e.reply(`AI画图已关闭`);
            return false;
        }
        // 检查CD;
        let tempCd = await redis.get(tempRedisCDkey);
        if (tempCd) {
            let timeRemaining = await redis.ttl(redisCDkey);
            e.reply(`AI画图还未完成，请稍后再试`);
            return false;
        }
        console.log(e.raw_message);
        const msg = e.raw_message.match(/(?<=AI画图 ).*/)[0];
        //检查是否包含违禁词
        if (msg.match(/nsfw/)) {
            e.reply("不许涩涩！");
            return false;
        }
        e.reply("正在生成图片，预计需要1分钟...");
        await redis.set(tempRedisCDkey, 1, { EX: 60 });
        this.getDraw("AI画图", msg, e);
    }
    async open(e) {
        if (e.user_id != cfg.masterQQ) {
            e.reply("你没有权限");
            return false;
        } else {
            let a = await redis.get(redisSwitchKey);
            if (a) {
                await redis.del(redisSwitchKey);
                e.reply("AI画图已开启");
                return true;
            } else {
                e.reply("AI画图已经开启了");
                return false;
            }
        }
    }
    async close(e) {
        if (e.user_id != cfg.masterQQ) {
            e.reply("你没有权限");
            return false;
        } else {
            redis.set(redisSwitchKey, 1);
            e.reply("AI画图已关闭");
            return true;
        }
    }
    async getDraw(drawMode, msg, e) {
        /**
         * 以下为浏览器操作
         */
        var steps = 0;
        if (drawMode == "快速画图") {
            console.log(`当前画图模式：${drawMode}`);
            steps = 14;
        }
        if (drawMode == "AI画图") {
            console.log(`当前画图模式：${drawMode}`);
            steps = 28;
        }
        const puppeteer = require("puppeteer"); //新建浏览器 大小为800*600
        const browser = await puppeteer.launch({
            headless: false,
        });
        const page = await browser.newPage();
        const downloadPath = path.resolve("./data/AIDraw");
        await page.goto(serverAddress);

        //设置下载路径
        await page._client.send("Page.setDownloadBehavior", {
            behavior: "allow",
            downloadPath: downloadPath,
        });

        //模拟输入steps
        await page.waitForSelector(
            "div.sc-jGNhvO.fgBnXq > div:nth-child(1) > input"
        );
        await page.click("div.sc-jGNhvO.fgBnXq > div:nth-child(1) > input");
        await page.type(
            "div.sc-jGNhvO.fgBnXq > div:nth-child(1) > input",
            steps.toString()
        );
        await page.waitForTimeout(1000);
        //模拟输入关键字
        await page.waitForSelector("#prompt-input-0");
        await page.type("#prompt-input-0", msg);

        const genButton = "div.sc-hTRxPq.jBtxjT > button";
        await page.waitForSelector(genButton);
        await page.click(genButton);
        const picture = "div > img";
        await page.waitForSelector(picture);
        //点击下载按钮
        const downloadButton = "div:nth-child(3) > button:nth-child(2)";
        await page.click(downloadButton);
        var files;
        for (let index = 0; index < 10; index++) {
            //等待 1000 ms
            await new Promise((resolve) => setTimeout(resolve, 1000));
            //查看下载文件夹中是否有msg[1].png文件
            files = fs.readdirSync(downloadPath);
            //将files[0]发送给用户
            if (files.length > 0) {
                break;
            }
        }
        await browser.close();
        //回复图片并at用户
        let recallCD = await redis.get(redisRecallKey);
        let msgRes = await e.reply([
            segment.at(e.user_id),
            segment.image(`${downloadPath}/${files[0]}`),
            `${recallCD}秒后图片将被自动撤回`,
        ]);
        //删除files[0]
        fs.unlinkSync(`${downloadPath}/${files[0]}`);
        await redis.del(tempRedisCDkey);
        if (recallCD != 0) {
            if (msgRes && msgRes.message_id) {
                setTimeout(() => {
                    e.group.recallMsg(msgRes.message_id);
                }, recallCD * 1000);
            }
        }
        return true;
    }
}
